#include<iostream>
#include<mysql/mysql.h>
#include<unistd.h>

const std::string host = "127.0.0.1";
const std::string user = "connector";
const std::string password = "123456";
const std::string db = "conn";
const unsigned int port = 3306;

int main()
{
    std::cout<<mysql_get_client_info()<<std::endl;

    MYSQL * my = mysql_init(nullptr);
    if(my == nullptr)
    {
        std::cerr<<"int mysql error"<<std::endl;
        return 1;
    }

    if(mysql_real_connect(my,host.c_str(),user.c_str(),password.c_str(),db.c_str(),port,nullptr,0) == nullptr)
    {
        std::cerr<<"connect mysql error"<<std::endl;
        return 2;
    }
    mysql_set_character_set(my,"utf8");
    // std::string sql = "update user set name='jimmy' where id=2";
    // std::string sql = "insert into user values (4,'张三',20,'12345677487')";
    // std::string sql = "delete from user where id = 1";
    std::string sql = "select * from user";
    int n = mysql_query(my,sql.c_str());
    if(n == 0)std::cout<<sql<<"  success"<<std::endl;
    else {
        std::cout<<sql<<"   fail"<<std::endl;
        return 3;
    }
    MYSQL_RES* res = mysql_store_result(my);
    if(res == nullptr)
    {
        std::cout<<sql<<"   fail"<<std::endl;
        return 4;
    }
    int rows = mysql_num_rows(res);
    int files = mysql_num_fields(res);

    std::cout<<rows<<std::endl;
    std::cout<<files<<std::endl;

    MYSQL_FIELD* filed_array = mysql_fetch_field(res);
    for(int i = 0; i < files ;i++)
    {
        std::cout<<filed_array[i].name<<"\t";
    }
    std::cout<<std::endl;

    for(int i = 0;i < rows;i++)
    {
        MYSQL_ROW row = mysql_fetch_row(res);
        for(int j = 0;j < files;j++)
        {
            std::cout<<row[j]<<"\t";
        }
        std::cout<<std::endl;
    }
    // while(true)
    // {
    //     std::cout<<"MYSQL>>>";
    //     if(!std::getline(std::cin,sql) || sql == "quit")
    //     {
    //         break;
    //     }
    //     int n = mysql_query(my,sql.c_str());
    //     if(n == 0)
    //     {
    //         std::cout<<sql<<"success"<<n<<std::endl;
    //     }
    //     else
    //     {
    //         std::cerr<<sql<<"fail"<<n<<std::endl;
    //         return 3;
    //     }
    // }
    // sleep(10);
    mysql_free_result(res);
    mysql_close(my);
    return 0;
}